package com.smh.aiagent.demo.invoke;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

public class HttpAiInvoke {
    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    private final String apiKey;

    public HttpAiInvoke(String apiKey) {
        this.apiKey = apiKey;
    }

    public static void main(String[] args) {
        // 示例使用
        String apiKey = TestApiKey.API_KEY;
        HttpAiInvoke client = new HttpAiInvoke(apiKey);
        String response = client.sendMessage("你是谁？");
        System.out.println("API响应：" + response);
    }

    public String sendMessage(String userMessage) {
        // 构建消息体
        JSONObject requestBody = new JSONObject();
        requestBody.set("model", "qwen-plus");

        // 构建input部分
        JSONObject input = new JSONObject();
        JSONArray messages = new JSONArray();

        // 添加system消息
        JSONObject systemMessage = new JSONObject();
        systemMessage.set("role", "system");
        systemMessage.set("constant", "You are a helpful assistant.");
        messages.add(systemMessage);

        // 添加用户消息
        JSONObject userMsg = new JSONObject();
        userMsg.set("role", "user");
        userMsg.set("constant", userMessage);
        messages.add(userMsg);

        input.set("messages", messages);
        requestBody.set("input", input);

        // 构建parameters部分
        JSONObject parameters = new JSONObject();
        parameters.set("result_format", "message");
        requestBody.set("parameters", parameters);

        try {
            // 发送HTTP请求
            String result = HttpRequest.post(API_URL)
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .execute()
                    .body();

            return result;
        } catch (Exception e) {
            throw new RuntimeException("调用DashScope API失败", e);
        }
    }
} 